//用户组管理

/**
 * 添加/编辑用户组视图模型
 */
interface IUserGroupManagentDetailViewModel {
    /**
     * 编号
     */
    id?: string;
    /**
     * 用户组名称
     */
    nameBox: string;
    /**
     * 权限值
     */
    roles: { role: string[] };
    click: () => void;
}

/**
 * 用户组视图模型
 */
interface IUserGroupManagentViewModel extends IBaseViewModel<IUserGroupManagentQueryTerms> {
    /**
     * 用户组列表组件配置信息
     */
    gridOptions: uiGrid.IGridOptionsOf<UserGroupListItemResponse>;
    /**
     * 添加/编辑视图
     */
    detail: IUserGroupManagentDetailViewModel;
    /**
     * 查询
     */
    query: () => void;
    /**
     * 添加用户组
     */
    addUserGroup: () => void;
    /**
     * 编辑用户组
     */
    editUserGroup: (id: string) => void;
    /**
     * 删除用户组
     */
    deleteUserGroup: (id: string) => void;
    /**
     * 列表高度
     */
    heightA: number;

    //权限列表
    authTree: ListResponse<visualAuthorizationListItemReponse>

    /**
    * 折叠h或者展开树
    */
    toggleTree: () => void
    /**
    * 树的展开状态
    */
    treeExpand: boolean;

    authNumbers: { high: number[], middle: number[], low: number[] }
    secAuthTypeTag: string[]

    saveChecked: number;

    saveCheckedAuth: () => void;
    /**
     * 编辑用户组权限
     */
    editUserGroupAuthorization: (any) => void;
    /**
     * 选中用户组的名称
     */
    UserGroupName: string;
}

/**
 * 查询条件
 */
interface IUserGroupManagentQueryTerms {
    /**
     * 用户组名称
     */
    name: string;
}

class UserGroupManagentController extends ListController<IUserGroupManagentViewModel, IUserGroupManagentQueryTerms> {
    gridApi: uiGrid.IGridApiOf<UserGroupListItemResponse>;
    selectedRow: any;
    constructor($scope: IUserGroupManagentViewModel, private userGroupService: IUserGroupService,
        private $ngBootbox: BootboxService, private visualAuthorizationService: visualAuthorizationService) {
        super($scope);
        this.init();
    }

    /**
     * 初始化
     */
    init(): void {
        super.init();
        this.$scope.addUserGroup = this.showAddUserGroupDialog;
        this.$scope.editUserGroup = this.showEditUserGroupDialog;
        this.$scope.deleteUserGroup = this.showDeleteUserGroupDialog;
        this.$scope.editUserGroupAuthorization = this.editUserGroupAuthorization;
        this.$scope.queryTerms = {
            name: ""
        };
        this.$scope.toggleTree = () => {
            this.$scope.treeExpand = !this.$scope.treeExpand
        }
        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 30],
            columnDefs: [
                { name: "序号", field: "index", enableColumnMenu: false },
                { name: "用户组名称", field: "name", enableColumnMenu: false },
                { name: "权限数", field: "authorizationCount", enableColumnMenu: false },
                { name: "用户数", field: "userCount", enableColumnMenu: false },
                {
                    name: "操作",
                    cellFilter: "checkmark",
                    cellTemplate: '<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" ng-click="grid.appScope.editUserGroup(row.entity.id)"></a> <a data-toggle="modal" data-target="#authModal" class="fa fa-pencil-square m-l-xs m-r-xs primary text-info" title="权限编辑" ng-click="grid.appScope.editUserGroupAuthorization(row.entity)"></a>  <a class="primary fa fa-trash-o text-danger" ng-click="grid.appScope.deleteUserGroup(row.entity.id)"></a>',
                    enableColumnMenu: false,
                    width: '6%'
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        this.$scope.query = this.query;
        this.query();

        this.$scope.authNumbers = {
            high: [],
            middle: [],
            low: []
        }

        this.$scope.secAuthTypeTag = [];
        this.$scope.UserGroupName = '';
        // this.visualAuthorizationService.getList().then(res=>{
        //     this.$scope.authTree=res.data

        // })
        this.$scope.saveChecked = 0
        this.$scope.saveCheckedAuth = this.saveCheckedAuth;

    }

    protected loadData(queryTerms: IUserGroupManagentQueryTerms, skip: number, count: number): void {
        this.userGroupService.getList(queryTerms.name, skip, count).then(result => {
            this.$scope.gridOptions.totalItems = result.data.total;
            this.$scope.gridOptions.data = result.data.data;
            result.data.data.map((item, index) => item.index = skip++ + 1);
            this.$scope.heightA = (this.$scope.gridOptions.data.length * 39) + 95;

            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

    /**
     * 显示添加用户组窗口
     */
    showAddUserGroupDialog = () => {
        $('#authorizationCheck').find('input[type="checkbox"]').prop("checked", false);
        this.$scope.title = "添加用户";
        this.$scope.detail = {
            nameBox: "",
            roles: { role: [] },
            click: this.addUserGroup
        };
    }

    addUserGroup = () => {
        if (!$("#userGroupForm").valid()) { return; }
        this.$ngBootbox.confirm("确定保存此数据吗？").then(e => {
            this.userGroupService.add(
                this.$scope.detail.nameBox,
                this.$scope.detail.roles.role
            ).then(result => {
                this.reload();
                $("#myModal").modal("hide");
            });
        });
    }

    /**
     * 显示编辑用户组窗口
     */
    showEditUserGroupDialog = (id: string) => {
        $("#authorizationRepeat").find("input[name='itemCheckN']").prop("checked", false);
        this.$scope.title = "编辑用户组";
        let validator = $('#userGroupForm').validate();//初始化表单验证
        validator.form();
        validator.hideErrors();
        $(".error").removeClass("error");

        this.userGroupService.getDetail(id).then(result => {
            this.$scope.detail = {
                id: id,
                nameBox: result.data.name,
                roles: { role: result.data.roles },
                click: this.editUserGroup
            }
        });
    }

    editUserGroup = () => {
        this.$ngBootbox.confirm("确定保存此数据吗？").then(e => {
            this.userGroupService.edit(
                this.$scope.detail.id,
                this.$scope.detail.nameBox,
                this.$scope.detail.roles.role
            ).then(result => {
                this.reload();
                $("#myModal").modal("hide");
            });
        });
    }

    /**
     * 删除用户组
     */
    showDeleteUserGroupDialog = (id: string) => {
        this.$ngBootbox.confirm("是否删除该数据").then(e => {
            this.userGroupService.delete(id).then(result => {
                this.reload();
            });
        });
    }

    /**
    * 编辑用户组权限
    */
    editUserGroupAuthorization = (row) => {
        this.$scope.UserGroupName = row.name;
        // console.log(row);
        this.visualAuthorizationService.getList(null, row.id,row.logisticsCompanyId).then(res => {
            this.$scope.authTree = res.data
        })
        this.$scope.treeExpand = false;
        // this.$scope.authNumbers={
        //     high:row.highAuthNumber,
        //     middle:row.middleAuthNumber,
        //     low:row.lowAuthNumber,
        // }
        this.selectedRow = row;
    }

    saveCheckedAuth = () => {
        // this.$scope.saveChecked++;

        this.$ngBootbox.confirm('确认保存数据吗').then(e => {
            console.log(e)
            // console.log(this.$scope.authNumbers,this.$scope.secAuthTypeTag);
            let checkedNumbers = { high: [], middle: [], low: [] }, secAuthTags = [];

            let nodes = this.$scope.authTree.data;
            nodes && nodes.forEach(firstAuth => {
                firstAuth.secAuthTypeList && firstAuth.secAuthTypeList.forEach(secNode => {
                    secNode.visualAuthList && secNode.visualAuthList.forEach(thNode => {
                        if (thNode.isShow) {
                            // checkedNumbers.push(thNode.authNumber);
                            let key = ['high', 'middle', 'low'][thNode.level - 1];
                            if (key) {

                                // console.log(checkedNumbers);
                                checkedNumbers[key].push(thNode.number);
                            }

                            if (secAuthTags.indexOf(thNode.secAuthorizationTypeTag) === -1) {
                                secAuthTags.push(thNode.secAuthorizationTypeTag);
                            }
                        }
                    })
                })

            })
            this.$scope.authNumbers = checkedNumbers;
            this.$scope.secAuthTypeTag = secAuthTags;
            let authObj = {
                HighAuthNumber: this.$scope.authNumbers.high,
                //中等级权限
                MiddleAuthNumber: this.$scope.authNumbers.middle,
                //低等级权限
                LowAuthNumber: this.$scope.authNumbers.low,
                //二级权限标签
                SecAuthTypeTag: this.$scope.secAuthTypeTag
            }
            this.userGroupService.editAuth(this.selectedRow.id, authObj).then(res => {
                // console.log(res)
                this.reload(this.$scope.gridOptions.paginationCurrentPage);
                $('#authModal').modal('hide');

            })
        })
    }

}
angular.module("tms").controller('userGroupManagentController', ['$scope', 'userGroupService', '$ngBootbox', 'visualAuthorizationService', UserGroupManagentController]);
